<template>
  <div class="container">
    <el-container>
      <el-header class="header">
        <el-menu
          class="navbar"
          mode="horizontal"
          :default-active="activeIndex"
          @select="handleSelect"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <template v-for="item in menuItems" :key="item.index">
            <el-sub-menu 
              v-if="item.children" 
              :index="item.index"
            >
              <template #title>
                <el-icon><component :is="item.icon" /></el-icon>
                <span>{{ item.label }}</span>
              </template>
              <el-menu-item
                v-for="child in item.children"
                :key="child.index"
                :index="child.index"
              >
                <el-icon><component :is="child.icon" /></el-icon>
                <span>{{ child.label }}</span>
              </el-menu-item>
            </el-sub-menu>

            <el-menu-item v-else :index="item.index">
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-header>

      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import apiClient from '../api';
import { homeMenus } from '../api/menus';

// 使用 computed 初始化 activeIndex
const route = useRoute();
const activeIndex = computed(() => route.params.index?.toString() || '0');

// 响应式数据
const menuItems = ref([...homeMenus]); // 克隆默认值
const router = useRouter();

// 事件处理
const handleSelect = (index) => {
  router.push(index === '0' ? '/' : `/pdf/${index}`);
};

// 生命周期
onMounted(() => {
  apiClient.get('/menus')
    .then(({ data }) => menuItems.value = data)
    .catch(console.error);
});
</script>

<style lang="scss" scoped>
.header {
  padding: 0;
  
  .navbar {
    width: 100%;
    box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.1);
  }
}

.main-content {
  padding: 0;
  min-height: calc(100vh - 60px);
}
</style>